import Dialog from '@vant/weapp/dialog/dialog'
import wxValidate from 'wechat-validate'

Page({
  behaviors: [wxValidate],
  data: {
    currentDate: new Date().getTime(),
    houseLayerVisible: false,
    repairLayerVisible: false,
    dateLayerVisible: false,

    houseId: '', // 选中的房屋id
    houseName: '', // 选中的房屋名称
    houseList: [],

    repairItemId: '', // 选中的维修项id
    repairItemName: '', // 选中的维修项名称
    repairItem: [],

    mobile: '', // 手机号
    appointment: '', // 预约日期
    description: '', // 问题描述

    attachment: [
      // { url: '/repair_pkg/static/uploads/attachment.jpg' },
      // { url: '/repair_pkg/static/uploads/attachment.jpg' },
    ],
  },

  rules: {
    houseId: [{ required: true, message: '请选择报修房屋!' }],
    repairItemId: [{ required: true, message: '请选择维修的项目!' }],
    mobile: [
      { required: true, message: '请填写手机号码!' },
      { pattern: /^1[3-8]\d{9}$/, message: '请填写正确的手机号码!' },
    ],
    appointment: [{ required: true, message: '请选择预约日期!' }],
    description: [{ required: true, message: '请填写问题描述!' }],
  },

  onDelAttachment(e) {
    // this.data.attachment.splice(e.detail.index, 1)
    // this.setData({ attachment: this.data.attachment })

    this.setData({
      attachment: this.data.attachment.filter((v) => v.id !== e.detail.file.id),
    })
  },

  async onSelectAttachment(e) {
    const promises = e.detail.file.map((v) => wx.http.uploadFile(v.tempFilePath, false, false))

    const results = await Promise.allSettled(promises)

    // 手动来关闭loading
    wx.hideLoading()

    console.log(results, 'results')

    // 给每个结果上添加一个index属性，目的：为了知道是第几张报错
    results.forEach((v, i) => (v.index = i))

    const successResults = results.filter((v) => v.status === 'fulfilled')
    const failResults = results.filter((v) => v.status === 'rejected')

    this.setData({
      attachment: [...this.data.attachment, ...successResults.map((v) => v.value.data)],
    })

    // 如果有失败的，就提示一下是哪几张
    if (failResults.length > 0) {
      // 为了让用户看清提示消息，用了一个alert，让用户手动关闭
      Dialog.alert({
        title: '上传失败',
        message: failResults
          .map((v) => {
            const { message } = JSON.parse(v.reason.data)
            return `第${v.index + 1}张：${message}`
          })
          .join('\r\n'),
      })
    }
  },

  setAppointment(e) {
    this.setData({
      appointment: wx.utils.formatTimestampToYYYYMMDDString(e.detail),
      dateLayerVisible: false,
    })
  },

  selectRepairItem(e) {
    const { id, name } = e.detail
    this.setData({ repairItemId: id, repairItemName: name })
  },

  selectHouse(e) {
    const { id, name } = e.detail
    this.setData({ houseId: id, houseName: name })
  },

  async openHouseLayer() {
    // 获取我的审核通过的房屋列表
    // const res = await wx.http({ url: '/house' })
    // this.setData({ houseList: res.data })

    // 获取我的房屋列表
    const res = await wx.http({ url: '/room' })
    this.setData({
      houseList: res.data.map((v) => ({
        id: v.id,
        name: v.point + v.building + v.room,
      })),

      houseLayerVisible: true,
    })
  },

  closeHouseLayer() {
    this.setData({ houseLayerVisible: false })
  },

  async openRepairLayer() {
    const res = await wx.http({ url: '/repairItem' })
    console.log(res)
    this.setData({
      repairItem: res.data,
      repairLayerVisible: true,
    })
  },

  closeRepairLayer() {
    this.setData({
      repairLayerVisible: false,
    })
  },

  openDateLayer() {
    this.setData({ dateLayerVisible: true })
  },

  closeDateLayer() {
    this.setData({ dateLayerVisible: false })
  },

  async onSubmit() {
    if (this.validate()) {
      // 提取需要的数据 比排除不要的数据 更严谨 可以防止日后添加新的数据 出现多余数据的问题
      const { houseId, repairItemId, mobile, appointment, description, attachment } = this.data
      const formData = { houseId, repairItemId, mobile, appointment, description, attachment }

      if (this.options.id) {
        formData.id = this.options.id
      }

      const res = await wx.http({
        method: 'post',
        url: '/repair',
        data: formData,
      })

      console.log(res, 'res')

      if (this.options.id) {
        // 修改成功

        // 1. 先获取页面栈
        const pages = getCurrentPages()
        // 2. 取到list页面实例
        const listPage = pages.find((v) => v.route === 'repair_pkg/pages/list/index')
        // 3. 调用list页面实例的updateRepairItem方法更新数据
        listPage.updateRepairItem({
          ...formData,
          houseInfo: this.data.houseName,
          repairItemName: this.data.repairItemName,
          status: this.data.status,
        })

        wx.navigateBack()
      } else {
        const pages = getCurrentPages()
        const pervPage = pages[pages.length - 2]

        // 如果上一个页面是列表页，就直接后退一步
        // 注意：route属性，不是以/开头的
        if (pervPage.route === 'repair_pkg/pages/list/index') {
          // 如果能够进入这个if判断，说明prevPage是什么页面实例？list页面实例

          pervPage.addRepairItemToListTop({
            ...formData,
            houseInfo: this.data.houseName,
            repairItemName: this.data.repairItemName,
            status: 1, // 新添加的报修信息，状态默认为：1-受理中
            id: res.data.id,
          })

          wx.navigateBack()
        } else {
          // 否者就重定向到列表页
          wx.redirectTo({
            // 跳转页面的时候，需要以/开头
            url: '/repair_pkg/pages/list/index',
          })
        }
      }
    }
  },

  async onLoad() {
    if (this.options.id) {
      // 有id，修改
      const res = await wx.http({ url: '/repair/' + this.options.id })
      this.setData({ ...res.data, houseName: res.data.houseInfo })
    }
  },
})
